package com.anjingsi.tools.test;

import java.math.BigDecimal;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @program: jaas-cloud-cxy
 * @description
 * @author: 安静思
 * @create: 2019-12-05 10:16
 **/
public class ForkJoinDemo {

    public static Long start = 0L;

    public static Long end = 2000000000L;

    public static void main(String[] args) {
//        forEach();    计算的结果为：2000000001000000000    ,耗时：10448
//        stream();     计算的结果为：2000000001000000000    ,耗时：600
        forkJoin();   //计算的结果为：2000000001000000000    ,耗时：11158
    }

    public static Long forEach(){
        Long sum = 0L;
        Long startTime = System.currentTimeMillis();
        for (int i = 0; i <= end; i++) {
            sum += i;
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("计算的结果为："+ sum + "    ,耗时："+(endTime-startTime));
        return null;
    }

    public static Long stream(){
        Long startTime = System.currentTimeMillis();
        long reduce = LongStream.rangeClosed(start, end).parallel().reduce(0L, Long::sum);
        Long endTime = System.currentTimeMillis();
        System.out.println("计算的结果为："+ reduce + "    ,耗时："+(endTime-startTime));
        return null;
    }

    public static Long forkJoin(){
        Long startTime = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinWork(startTime,end);
        Long reduce = pool.invoke(task);
        Long endTime = System.currentTimeMillis();
        System.out.println("计算的结果为："+ reduce + "    ,耗时："+(endTime-startTime));
        return null;
    }

}


